package com.aliyunlog.utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;

/**
 *
 * @author tanson lam
 * @creation 2017年6月25日
 * 
 */
public class DingDingWarnUtil {

	/**
	 * 发送钉钉消息
	 * 
	 * @param Url
	 * @param message
	 * @throws IOException
	 * @throws ParseException
	 * @throws @throws
	 *             Exception
	 */
	public static String sendDingtalk(String url, String text) throws Exception {
		HttpPost httppost = new HttpPost(url);
		httppost.addHeader("Content-Type", "application/json; charset=utf-8");

		Map<String, Object> items = new HashMap<String, Object>();
		items.put("msgtype", "text");
		Map<String, String> textContent = new HashMap<String, String>();
		if (StringUtils.isBlank(text)) {
			throw new IllegalArgumentException("text should not be blank");
		}
		textContent.put("content", text);
		items.put("text", textContent);
		String textMsg = JSON.toJSONString(items);
		StringEntity se = new StringEntity(textMsg, "utf-8");
		httppost.setEntity(se);

		HttpResponse response = new DefaultHttpClient().execute(httppost);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			return EntityUtils.toString(response.getEntity(), "utf-8");
		}
		return null;
	}
}
